﻿import dayjs from 'dayjs'

import useCurrentUser from '../app/hooks/useCurrentUser'
import { useEffect, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useAuthStore } from '../app/store/authStore'
import { AuthAPI } from '../app/api'

const ProfilePage = () => {
  const { data: user, isLoading } = useCurrentUser()
  const qc = useQueryClient()
  const [nickname, setNickname] = useState<string>('')
  const [saving, setSaving] = useState(false)
  useEffect(() => {
    setNickname(user?.nickname ?? '')
  }, [user?.nickname])
  const refreshToken = useAuthStore((state) => state.refreshToken)
  const logout = useAuthStore((state) => state.logout)

  const partnerProfile = user?.partner_profile
  useEffect(() => {
    if (typeof document !== 'undefined') {
      document.title = '我的 · Love Notes'
    }
  }, [])

  return (
    <div className="space-y-6">
      <section className="rounded-3xl border border-slate-100 bg-white/90 p-6 shadow-card">
        <h2 className="text-lg font-semibold text-slate-900">账号信息</h2>
        <p className="mt-2 text-sm text-slate-500">管理登录邮箱与退出登录，刷新令牌会在注销时一并失效。</p>
        <div className="mt-4 space-y-3">
          <div className="rounded-2xl border border-slate-100 bg-slate-50/80 px-4 py-3 text-sm text-slate-600">
            <span className="block text-xs uppercase tracking-wide text-slate-400">邮箱</span>
            <span className="text-base font-semibold text-slate-900">{user?.email ?? '未知'}</span>
          </div>
          <button
            onClick={async () => {
              if (refreshToken) {
                await AuthAPI.logout(refreshToken).catch(() => undefined)
              }
              logout()
              window.location.replace('/auth')
            }}
            className="w-full rounded-full bg-red-500 px-4 py-3 text-sm font-semibold text-white shadow-card transition hover:bg-red-600"
          >
            退出登录
          </button>
        </div>
      </section>
      <section className="rounded-3xl border border-slate-100 bg-white/90 p-6 shadow-card">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <h2 className="text-lg font-semibold text-slate-900">情侣资料</h2>
            <p className="mt-2 text-sm text-slate-500">这些信息会用于生成个性化提醒与 AI 建议。</p>
          </div>
          <div className="flex flex-wrap items-end gap-3">
            <div className="text-sm">
              <label className="block text-xs text-slate-500">我的昵称</label>
              <input
                className="rounded-lg border border-slate-200 px-3 py-1.5 text-sm"
                placeholder="如：小明/阿蛋"
                value={nickname}
                onChange={(e) => setNickname(e.target.value)}
              />
            </div>
            <button
              className="rounded-lg bg-blush-500 px-3 py-2 text-xs font-semibold text-white disabled:opacity-60"
              disabled={saving}
              onClick={async () => {
                setSaving(true)
                try {
                  await AuthAPI.updateProfile({ nickname: nickname || null })
                  await qc.invalidateQueries({ queryKey: ['me'] })
                } finally {
                  setSaving(false)
                }
              }}
            >
              {saving ? '保存中...' : '保存'}
            </button>
          </div>
        </div>
        {isLoading ? (
          <p className="mt-4 text-sm text-slate-400">资料加载中...</p>
        ) : (
          <div className="mt-6 grid gap-4 sm:grid-cols-2">
            <ProfileCard title="邮箱" value={user?.email ?? '—'} />
            <ProfileCard title="用户名" value={user?.username ?? '—'} />
            <ProfileCard title="伴侣昵称" value={user?.partner_display_name ?? '未绑定或未填写'} />
            <ProfileCard
              title="关系开始时间"
              value={user?.relationship_started_at ? dayjs(user.relationship_started_at).format('YYYY-MM-DD') : '未设置'}
            />
          </div>
        )}
      </section>
      {/* 共同目标模块已移除 */}
    </div>
  )
}

const ProfileCard = ({ title, value }: { title: string; value: string }) => (
  <div className="rounded-2xl border border-slate-100 bg-slate-50/80 p-4">
    <p className="text-xs font-medium uppercase tracking-widest text-slate-400">{title}</p>
    <p className="mt-2 text-base font-semibold text-slate-900">{value}</p>
  </div>
)

export default ProfilePage
